# 退费审核管理系统 - Nginx部署脚本 (PowerShell版本)
# 使用方法：在PowerShell中运行 .\deploy-nginx.ps1

# 设置控制台编码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "    退费审核管理系统 - Nginx部署脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 函数：显示步骤
function Write-Step {
    param([string]$StepNumber, [string]$Description)
    Write-Host "[$StepNumber] $Description..." -ForegroundColor Yellow
}

# 函数：显示成功信息
function Write-Success {
    param([string]$Message)
    Write-Host "✅ $Message" -ForegroundColor Green
}

# 函数：显示错误信息
function Write-Error-Custom {
    param([string]$Message)
    Write-Host "❌ 错误：$Message" -ForegroundColor Red
}

# 函数：显示警告信息
function Write-Warning-Custom {
    param([string]$Message)
    Write-Host "⚠️  警告：$Message" -ForegroundColor Yellow
}

try {
    # 步骤1：检查Node.js环境
    Write-Step "1/7" "检查Node.js环境"
    $nodeVersion = $null
    try {
        $nodeVersion = node --version 2>$null
        if ($nodeVersion) {
            Write-Success "Node.js环境检查通过 (版本: $nodeVersion)"
        } else {
            throw "Node.js未安装"
        }
    } catch {
        Write-Error-Custom "未找到Node.js，请先安装Node.js"
        Write-Host "下载地址：https://nodejs.org/" -ForegroundColor Blue
        Read-Host "按任意键退出"
        exit 1
    }
    Write-Host ""

    # 步骤2：检查npm环境
    Write-Step "2/7" "检查npm环境"
    $npmVersion = $null
    try {
        $npmVersion = npm --version 2>$null
        if ($npmVersion) {
            Write-Success "npm环境检查通过 (版本: $npmVersion)"
        } else {
            throw "npm不可用"
        }
    } catch {
        Write-Error-Custom "npm不可用"
        Read-Host "按任意键退出"
        exit 1
    }
    Write-Host ""

    # 步骤3：检查项目文件
    Write-Step "3/7" "检查项目文件"
    if (-not (Test-Path "package.json")) {
        Write-Error-Custom "未找到package.json文件，请确保在正确的项目目录中运行此脚本"
        Read-Host "按任意键退出"
        exit 1
    }
    Write-Success "项目文件检查通过"
    Write-Host ""

    # 步骤4：安装依赖
    Write-Step "4/7" "安装项目依赖"
    if (-not (Test-Path "node_modules")) {
        Write-Host "正在安装依赖，请稍候..." -ForegroundColor Blue
        $installResult = npm install 2>&1
        if ($LASTEXITCODE -ne 0) {
            Write-Error-Custom "依赖安装失败"
            Write-Host $installResult -ForegroundColor Red
            Read-Host "按任意键退出"
            exit 1
        }
    } else {
        Write-Host "依赖已存在，跳过安装" -ForegroundColor Blue
    }
    Write-Success "依赖安装完成"
    Write-Host ""

    # 步骤5：构建项目
    Write-Step "5/7" "构建生产版本"
    Write-Host "正在构建，请稍候..." -ForegroundColor Blue
    
    # 删除旧的构建文件
    if (Test-Path "dist") {
        Remove-Item -Recurse -Force "dist"
        Write-Host "已清理旧的构建文件" -ForegroundColor Blue
    }
    
    $buildResult = npm run build 2>&1
    if ($LASTEXITCODE -ne 0) {
        Write-Error-Custom "构建失败"
        Write-Host $buildResult -ForegroundColor Red
        Read-Host "按任意键退出"
        exit 1
    }
    Write-Success "项目构建完成"
    Write-Host ""

    # 步骤6：检查构建结果
    Write-Step "6/7" "检查构建结果"
    if (-not (Test-Path "dist")) {
        Write-Error-Custom "dist目录不存在"
        Read-Host "按任意键退出"
        exit 1
    }
    if (-not (Test-Path "dist\index.html")) {
        Write-Error-Custom "index.html文件不存在"
        Read-Host "按任意键退出"
        exit 1
    }
    
    # 计算构建文件大小
    $distSize = (Get-ChildItem -Recurse "dist" | Measure-Object -Property Length -Sum).Sum
    $distSizeMB = [math]::Round($distSize / 1MB, 2)
    
    Write-Success "构建文件检查通过 (总大小: $distSizeMB MB)"
    Write-Host ""

    # 步骤7：生成部署信息
    Write-Step "7/7" "生成部署信息"
    
    $currentPath = Get-Location
    $distPath = Join-Path $currentPath "dist"
    $nginxConfigPath = Join-Path $currentPath "nginx.conf"
    $deployGuidePath = Join-Path $currentPath "Nginx部署指南.md"
    
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "🎉 前端构建完成！" -ForegroundColor Green
    Write-Host ""
    Write-Host "📁 构建文件位置：$distPath" -ForegroundColor Blue
    Write-Host "📄 Nginx配置文件：$nginxConfigPath" -ForegroundColor Blue
    Write-Host "📖 部署指南：$deployGuidePath" -ForegroundColor Blue
    Write-Host ""
    Write-Host "🚀 接下来的步骤：" -ForegroundColor Yellow
    Write-Host "1. 安装Nginx（如果尚未安装）" -ForegroundColor White
    Write-Host "2. 将nginx.conf复制到Nginx配置目录" -ForegroundColor White
    Write-Host "3. 修改nginx.conf中的root路径为：$distPath" -ForegroundColor White
    Write-Host "4. 启动Nginx服务" -ForegroundColor White
    Write-Host "5. 访问 http://localhost:8089/his-refund/" -ForegroundColor White
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host ""
    
    Write-Success "部署信息生成完成"
    Write-Host ""

    # 询问用户操作
    $openGuide = Read-Host "是否打开部署指南？(Y/N)"
    if ($openGuide -eq "Y" -or $openGuide -eq "y") {
        if (Test-Path $deployGuidePath) {
            Start-Process $deployGuidePath
        } else {
            Write-Warning-Custom "部署指南文件不存在"
        }
    }

    $openDist = Read-Host "是否打开构建目录？(Y/N)"
    if ($openDist -eq "Y" -or $openDist -eq "y") {
        if (Test-Path $distPath) {
            Start-Process "explorer.exe" -ArgumentList $distPath
        } else {
            Write-Warning-Custom "构建目录不存在"
        }
    }

    $copyConfig = Read-Host "是否需要帮助配置Nginx？(Y/N)"
    if ($copyConfig -eq "Y" -or $copyConfig -eq "y") {
        Write-Host ""
        Write-Host "Nginx配置帮助：" -ForegroundColor Yellow
        Write-Host "1. 如果您已安装Nginx，请将以下路径添加到nginx.conf中：" -ForegroundColor White
        Write-Host "   root $distPath;" -ForegroundColor Green
        Write-Host ""
        Write-Host "2. 或者直接使用项目提供的完整配置文件：" -ForegroundColor White
        Write-Host "   $nginxConfigPath" -ForegroundColor Green
        Write-Host ""
        Write-Host "3. 常用Nginx命令：" -ForegroundColor White
        Write-Host "   启动：nginx.exe" -ForegroundColor Green
        Write-Host "   停止：nginx -s stop" -ForegroundColor Green
        Write-Host "   重载：nginx -s reload" -ForegroundColor Green
        Write-Host "   测试：nginx -t" -ForegroundColor Green
    }

} catch {
    Write-Error-Custom "部署过程中发生错误：$($_.Exception.Message)"
    Write-Host $_.ScriptStackTrace -ForegroundColor Red
} finally {
    Write-Host ""
    Write-Host "部署脚本执行完成！" -ForegroundColor Cyan
    Read-Host "按任意键退出"
}